import React, { useCallback } from 'react';
import clsx from 'clsx';
import {
  SearchOutlined,
  ClockCircleOutlined,
  FireOutlined,
  RiseOutlined
} from '@ant-design/icons';
import type { SearchSuggestionsProps, SearchSuggestion } from '@/types';
import styles from './SearchSuggestions.module.css';

/**
 * 搜索建议组件
 */
export const SearchSuggestions: React.FC<SearchSuggestionsProps> = ({
  suggestions,
  onSelect,
  onClose,
  visible = true,
  loading = false,
  maxItems = 10,
  highlightQuery = '',
  position = 'bottom',
  selectedIndex = -1,
  className,
  testId,
  ...props
}) => {
  // 限制显示数量
  const displaySuggestions = suggestions.slice(0, maxItems);
  
  // 获取建议项图标
  const getSuggestionIcon = useCallback((suggestion: SearchSuggestion) => {
    switch (suggestion.type) {
      case 'history':
        return <ClockCircleOutlined className={styles.icon} />;
      case 'trending':
        return <FireOutlined className={styles.icon} />;
      case 'suggestion':
        return <SearchOutlined className={styles.icon} />;
      default:
        return <SearchOutlined className={styles.icon} />;
    }
  }, []);
  
  // 高亮查询文本
  const highlightText = useCallback((text: string, query: string) => {
    if (!query.trim()) return text;
    
    const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    const parts = text.split(regex);
    
    return parts.map((part, index) => {
      if (regex.test(part)) {
        return (
          <mark key={index} className={styles.highlight}>
            {part}
          </mark>
        );
      }
      return part;
    });
  }, []);
  
  // 处理建议项点击
  const handleSuggestionClick = useCallback((suggestion: SearchSuggestion) => {
    onSelect(suggestion);
  }, [onSelect]);
  
  // 处理键盘事件
  const handleKeyDown = useCallback((e: React.KeyboardEvent, suggestion: SearchSuggestion) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      onSelect(suggestion);
    }
  }, [onSelect]);
  
  // 如果不可见或没有建议，不渲染
  if (!visible || displaySuggestions.length === 0) {
    return null;
  }
  
  // 构建样式类名
  const containerClasses = clsx(
    styles.container,
    styles[`container--${position}`],
    {
      [styles['container--loading']]: loading,
    },
    className
  );
  
  return (
    <div
      className={containerClasses}
      data-testid={testId}
      role="listbox"
      aria-label="搜索建议"
      {...props}
    >
      {loading ? (
        // 加载状态
        <div className={styles.loading}>
          <div className={styles.loadingSpinner} />
          <span className={styles.loadingText}>正在获取建议...</span>
        </div>
      ) : (
        // 建议列表
        <ul className={styles.list} role="none">
          {displaySuggestions.map((suggestion, index) => (
            <li
              key={suggestion.id}
              className={clsx(styles.item, {
                [styles['item--selected']]: index === selectedIndex,
                [styles['item--trending']]: suggestion.type === 'trending',
                [styles['item--history']]: suggestion.type === 'history',
              })}
              role="option"
              aria-selected={index === selectedIndex}
              tabIndex={-1}
              onClick={() => handleSuggestionClick(suggestion)}
              onKeyDown={(e) => handleKeyDown(e, suggestion)}
            >
              {/* 建议项图标 */}
              <div className={styles.iconWrapper}>
                {getSuggestionIcon(suggestion)}
              </div>
              
              {/* 建议项内容 */}
              <div className={styles.content}>
                <div className={styles.text}>
                  {highlightText(suggestion.text, highlightQuery)}
                </div>
                
                {/* 建议项元数据 */}
                {suggestion.metadata && (
                  <div className={styles.metadata}>
                    {suggestion.metadata.category && (
                      <span className={styles.category}>
                        {suggestion.metadata.category}
                      </span>
                    )}
                    
                    {suggestion.metadata.resultCount && (
                      <span className={styles.resultCount}>
                        约 {suggestion.metadata.resultCount.toLocaleString()} 个结果
                      </span>
                    )}
                    
                    {suggestion.type === 'trending' && suggestion.metadata.popularity && (
                      <span className={styles.popularity}>
                        <RiseOutlined className={styles.trendIcon} />
                        热度 {suggestion.metadata.popularity}
                      </span>
                    )}
                  </div>
                )}
              </div>
              
              {/* 建议项操作 */}
              <div className={styles.actions}>
                {suggestion.frequency && (
                  <span className={styles.frequency}>
                    {suggestion.frequency > 1000 
                      ? `${(suggestion.frequency / 1000).toFixed(1)}k` 
                      : suggestion.frequency
                    }
                  </span>
                )}
              </div>
            </li>
          ))}
        </ul>
      )}
      
      {/* 底部提示 */}
      {!loading && displaySuggestions.length > 0 && (
        <div className={styles.footer}>
          <span className={styles.tip}>
            使用 ↑↓ 键导航，回车键选择
          </span>
        </div>
      )}
    </div>
  );
};

export default SearchSuggestions;
